<template>
  <div class="aui-wrapper aui-page__login">
    <div class="aui-content__wrapper">
      <main class="aui-content page-content login-bg-img"
            :style="{backgroundImage:'url('+$ossLink+'/app/gif/'+$store.state.siteWebConfig.login_bgimg+')'}">
        <div class="login-header"></div>
        <div style="position: absolute;left: 0px;right: 0px;top: 0px;bottom: 0px;background: rgba(0, 0, 0, 0.2);backdrop-filter: blur(8px);"></div>
        <div style="display: flex;z-index: 9999;opacity: 1;border: 1px solid rgba(0,0,0,0.08);border-radius: 8px;overflow: hidden;">
          <div style="">
            <img :src="$ossLink + '/app/gif/'+$store.state.siteWebConfig.login_img"
                 :alt="$t('clientPortalLogin.mspbots')" />
          </div>
          <div class="login-body"
               style="padding: 0px 0px;">
            <div style="
                padding-top: 10px;
                padding-left: 30px;
                background-color: #00000014 !important;
                font-size: 30px;
                text-align: initial;
                height: 80px;
                margin: auto;
                font-family: inherit;
                line-height: 2 !important;
                color: #000000E6;
                opacity: 1;
                border: 1px solid rgba(0,0,0,0.08)
              ">
              请登录
            </div>
            <el-form style="padding: 30px 30px; margin-top: 30px"
                     :model="dataForm"
                     :rules="dataRule"
                     size="small"
                     v-loading="loading"
                     ref="dataForm"
                     @keyup.enter.native="dataFormSubmitHandle()"
                     status-icon>
              <div>
                <el-form-item prop="username">
                  <el-input v-model="dataForm.username"
                            :placeholder="$t('login.username')">
                    <span slot="prefix"
                          class="el-input__icon">
                      <svg class="icon-svg"
                           aria-hidden="true">
                        <use xlink:href="#icon-user"></use>
                      </svg>
                    </span>
                  </el-input>
                </el-form-item>
                <el-form-item prop="password">
                  <el-input v-model="dataForm.password"
                            type="password"
                            show-password
                            :placeholder="$t('login.password')">
                    <span slot="prefix"
                          class="el-input__icon">
                      <svg class="icon-svg"
                           aria-hidden="true">
                        <use xlink:href="#icon-lock"></use>
                      </svg>
                    </span>
                  </el-input>
                </el-form-item>
                <el-form-item style="text-align: left">
                  <el-checkbox v-model="isRememberAccount">{{
                    $t('clientPortalLogin.rememberAccount')
                  }}</el-checkbox>
                </el-form-item>
                <el-form-item>
                  <el-button size="small"
                             type="primary"
                             style="background-color: #0043ce; border-color: #0043ce;font-size:14px;"
                             v-loading="loading"
                             @click="dataFormSubmitHandle()"
                             class="w-percent-100">{{ $t('login.title') }}</el-button>
                </el-form-item>
              </div>
              <!-- <el-form-item>
                <el-button size="small"
                          :loading="loading"
                          @click="goRegist()"
                          class="w-percent-100">{{ $t('regist.title') }}</el-button>
              </el-form-item> -->
            </el-form>
          </div>
        </div>
        <div class="login-footer">
          <div style="
              color: #aab2d5;
              font-weight: bold;
              display: flex;
              align-items: center;
              justify-content: space-between;
            ">
            <!-- <div @click="toOtherPage('termsOfUse')">{{ $t('custom.login.termsOfUse') }}</div>
            <div @click="toOtherPage('compliance')">{{ $t('custom.login.compliance') }}</div>
            <div @click="toOtherPage('support')">{{ $t('custom.login.support') }}</div>
            <div @click="toOtherPage('contacts')">{{ $t('custom.login.contacts') }}</div> -->
          </div>
          <!-- <p style="color:#C2C9E9;">{{ $t('custom.login.tips') }}</p> -->
        </div>
      </main>
    </div>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import debounce from 'lodash/debounce'
import { getUUID } from '@/utils'
import { getDictInfoCommon } from '@/utils/common-request'
import { setToken } from '@/components/storybook/utilties/auth'

export default {
  data () {
    return {
      dataForm: {
        username: '',
        password: '',
        uuid: ''
      },
      loading: false,
      isRememberAccount: false,
      beforeLoginPage: null,
      beforeLoginParams: null
    }
  },
  computed: {
    dataRule () {
      return {
        username: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur',
            pattern: '[^ \x22]+'
          },
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ]
      }
    },
    img0 () {
      return this.$ossLink + '/app/gif/login_image.gif'
    }
  },
  created () {
    Promise.all([this.getloginInfo()]).then(() => {
      this.getCaptcha()
      this.accountFill()
      if (
        this.$store.state.app.isNavToLogin &&
        this.$store.state.app.beforeLoginPage &&
        this.$store.state.app.beforeLoginPage !== '/'
      ) {
        this.beforeLoginPage = this.$store.state.app.beforeLoginPage
        this.beforeLoginParams = this.$store.state.app.beforeLoginParams
      }
    })
  },
  methods: {
    getloginInfo () {
      this.loading = true
      this.$interface.other.getLoginConfigInfo({}).then(({data:res}) => {
        let tempHost = window.location.hostname
        if(tempHost && tempHost !== 'localhost' && res.data.length > 0) {         
          this.$store.state.siteWebConfig = res.data.filter(e=>e.origin === tempHost)[0]
        }
      }).finally(() => {
        this.loading = false
      })
    },
    getCaptcha () {
      this.dataForm.uuid = getUUID()
    },
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs['dataForm'].validate(valid => {
          if (!valid) {
            return
          }
          this.dataForm.username = this.dataForm.username.trim()
          this.loading = true
          this.rememberAccount()
          this.$interface.login
            .webLoginApi(this.dataForm)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                this.loading = false
                this.getCaptcha()
                this.clearnLocal()
                return this.$message.error(res.msg)
              }
              this.handleSignInWithButtonSuccess(res.data)

              this.loginSuccess(res.data)
              getDictInfoCommon()
            })
            .catch(error => {
              console.log(error, 'error')
              this.clearnLocal()
              this.loading = false
            })
        })
      },
      1000,
      { leading: true, trailing: false }
    ),
    async handleSignInWithButtonSuccess (data) {
      this.setCookies(data)
      this.setTabs()

      this.$store
        .dispatch('generateUser')
        .catch(error => console.error(error, 'get user info error'))

      this.authRoutingJump()
    },
    setCookies (data) {
      const { token, tenantCode, tenantName } = data || {}
      setToken(token, { sameSite: 'None', secure: true })
      Cookies.set('tenant_code', tenantCode, { sameSite: 'None', secure: true })
      window.sessionStorage.setItem('isMySelfCode', tenantCode)
      window.sessionStorage.setItem('isMySelfName', tenantName)
    },

    async setTabs () {
      this.$store.state.contentTabs = window.SITE_CONFIG[
        'routerWithForgetToken'
      ] || [
          {
            ...window.SITE_CONFIG['contentTabDefault'],
            name: 'home',
            title: 'home'
          }
        ]
    },
    async authRoutingJump () {
      let query = window.userFormQuery
      if (query && has(query, 'formCode')) {
        return this.$router.push(
          {
            path: '/userForm',
            query: query
          },
          this.completeRoutingJump
        )
      }

      if (this.redirect) {
        return this.$router.push(this.redirect, this.completeRoutingJump)
      }

      if (
        window.sessionStorage.getItem('isLoginRouter') &&
        window.sessionStorage.getItem('isLoginRouterPath')
      ) {
        return this.$router.push(
          { path: window.sessionStorage.getItem('isLoginRouterPath') },
          this.completeRoutingJump
        )
      }

      if (
        this.$store.state.app.beforeLoginPage &&
        this.$store.state.app.isNavToLogin
      ) {
        return this.$router.push(
          {
            path:
              this.$store.state.app.beforeLoginPage +
              this.$store.state.app.beforeLoginParams
          },
          this.completeRoutingJump
        )
      }

      return this.$router.push(
        {
          path: '/'
        },
        this.completeRoutingJump
      )
    },

    completeRoutingJump () {
      this.$store.state.app.isNavToLogin = false
      this.$store.state.app.beforeLoginPage = null
      this.$store.state.app.beforeLoginParams = null
      sessionStorage.removeItem('isLoginRouterPath')
      sessionStorage.removeItem('isLoginRouter')
    },
    loginSuccess (data) {
      this.$interface.login
        .loginUserInfoApi()
        .then(res => {
          this.loading = false
          if (res.data.code !== 0) {
            this.$store.commit('SET_API_LOAD_STATUS', false)
            return this.$message.error(res.data.msg)
          }
        })
        .catch(() => {
          this.loading = false
          this.$store.commit('SET_API_LOAD_STATUS', false)
        })
    },
    setCookies (data) {
      window.location.protocol === 'https:'? Cookies.set('token', data.token, { sameSite: 'None', secure: true }): Cookies.set('token', data.token)
      window.location.protocol === 'https:'? Cookies.set('tenant_code', data.tenantCode, { sameSite: 'None',secure: true}): Cookies.set('tenant_code', data.tenantCode)
      sessionStorage.setItem('isMySelfCode', data.tenantCode)
      sessionStorage.setItem('isMySelfName', data.tenantName)
    },
    goRegist () {
      this.$router.replace({ path: '/registAsAccount' })
    },
    toOtherPage (e) {
      const support = 'https://wiki.mspbots.ai/x/JogF'
      const contacts = 'https://mspbots.ai'
      const termsOfUse = 'https://mspbots.ai/termsofuse/'
      const compliance = 'https://mspbots.ai/privacy/'
      switch (e) {
        case 'termsOfUse':
          window.open(termsOfUse, '_blank')
          break
        case 'compliance':
          window.open(compliance, '_blank')
          break
        case 'support':
          window.open(support, '_blank')
          break
        case 'contacts':
          window.open(contacts, '_blank')
          break
        default:
          break
      }
    },
    rememberAccount () {
      if (this.isRememberAccount) {
        localStorage.setItem('portalaccounta', this.dataForm.username)
        localStorage.setItem('portalaccountb', this.dataForm.password)
        localStorage.setItem('portalaccountc', this.isRememberAccount)
      } else {
        localStorage.removeItem('portalaccounta')
        localStorage.removeItem('portalaccountb')
        localStorage.removeItem('portalaccountc')
      }
    },
    accountFill () {
      if (
        localStorage.getItem('portalaccountc') &&
        localStorage.getItem('portalaccounta') &&
        localStorage.getItem('portalaccountb')
      ) {
        this.$set(
          this.dataForm,
          'username',
          localStorage.getItem('portalaccounta')
        )
        this.$set(
          this.dataForm,
          'password',
          localStorage.getItem('portalaccountb')
        )
        this.$nextTick(() => {
          this.dataFormSubmitHandle()
        })
      }
    },
    clearnLocal () {
      if (localStorage.getItem('portalaccounta'))
        localStorage.removeItem('portalaccounta')
      if (localStorage.getItem('portalaccountb'))
        localStorage.removeItem('portalaccountb')
      if (localStorage.getItem('portalaccountc'))
        localStorage.removeItem('portalaccountc')
    }
  }
}
</script>
<style lang="scss" scoped>
.aui-page__login::before {
  background-image: none;
  background: #f2f4f8;
}
.aui-page__login .aui-content__wrapper {
  background-color: #f2f4f8;
}
.page-content {
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
.login-icon {
  width: 100%;
  //height: 55px;
  margin-bottom: 20px;
  img {
    width: 90%;
    margin-right: 55px;
  }
}

.hide {
  display: none;
}

.login-footer > div > div {
  cursor: pointer;
}
</style>
